//
//  CNOauthViewController.swift
//  Ccweibo
//
//  Created by 陈锦聪 on 16/3/21.
//  Copyright © 2016年 Coco. All rights reserved.
//

import UIKit
import SVProgressHUD

class CNOauthViewController: UIViewController {
   
    private lazy var webView: UIWebView = UIWebView()
    // 在loadView中设置的webView默认和view一样大
    override func loadView() {
        view = webView
        
        webView.delegate = self
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.whiteColor()
        
        setupNavigationBar()
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
//        print(urlString)
        let url = NSURL(string: urlString)
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)
        SVProgressHUD.showWithStatus("正在加载页面", maskType: SVProgressHUDMaskType.Black)
    }

    private func setupNavigationBar() {
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "我的", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFillAccount")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancelLogin")
    }
    
    func autoFillAccount() {
        
        let JSCode = "document.getElementById('userId').value='coco_12666@sina.com';document.getElementById('passwd').value='std12666.com'"
        webView.stringByEvaluatingJavaScriptFromString(JSCode)
        
    }
    
    func cancelLogin() {
        
        dismissViewControllerAnimated(true, completion: nil)
    }
}
// MARK: - UIWebViewDelegate
extension CNOauthViewController: UIWebViewDelegate {
    
    func webViewDidFinishLoad(webView: UIWebView) {
        
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let absString = request.URL!.absoluteString
        // 不是授权回调地址,直接加载请求
        if !absString.hasPrefix(redirect_uri) {
            return true
        }
        // 请求地址是授权回调地址,表明点击了授权或取消
        // query: ?后面的请求参数
        let query = request.URL?.query
        // 授权成功返回结果为: 'code=...'
        let codeString = "code="
        // 点击了授权
        if  query!.hasPrefix(codeString) {
            
            let nsQuery = query! as NSString
            let code = nsQuery.substringFromIndex(codeString.characters.count)
            // 加载access_Token
            CNUserAccountViewModel.sharedInstance.loadAccessToken(code, completion: { (error) -> () in
                // 获取授权失败
                if error != nil {
                    SVProgressHUD.showErrorWithStatus("获取授权令牌失败")
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                        self.cancelLogin()
                    })
                } else {
                    // 获取授权成功
                    self.cancelLogin()
                    AppDelegate.loadViewController(CNWelcomeViewController())
                }
            })
        } else {
            // 点击了取消
            cancelLogin()
        }
        return false
    }    
}
